<template>
  <el-dialog
    :title="title"
    :modal="false"
    :draggable="true"
    :model-value="modelValue"
    width="80%"
    class="userAlarm-dialog"
    append-to-body
    @update:modelValue="handleClose"
  >
    <el-tabs v-model="activeName" class="tabs-box" @tab-click="handleClick">
      <el-tab-pane label="入户监测分析" name="first">
        <div class="card-box">
          <div class="card-item" v-for="(item, index) in projectNum" :key="index">
            <img :src="item.icon" alt="暂无" />
            <div class="card-item-content">
              <div class="num">{{ item.num }}</div>
              <div class="name">{{ item.name }}</div>
            </div>
          </div>
        </div>
        <el-row :gutter="10" type="flex" align="middle" justify="space-between">
          <el-col :span="10">
            <h3>设备各区县安装情况分布</h3>
            <div :style="styleObject">
              <ECharts :options="County" v-if="activeName === 'first'" />
            </div>
          </el-col>
          <el-col :span="10">
            <h3>各区县设备报警分布</h3>
            <div :style="styleObject">
              <ECharts :options="AlarmCounty" v-if="activeName === 'first'" />
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10" type="flex" align="middle" justify="space-between">
          <el-col :span="10">
            <h3>各区县设备安装数量和报警数量</h3>
            <div :style="styleObject">
              <ECharts :options="CountyAndHouse" v-if="activeName === 'first'" />
            </div>
          </el-col>
          <el-col :span="10">
            <h3>报警时间处置趋势</h3>
            <div :style="styleObject">
              <ECharts :options="AlarmByTime" v-if="activeName === 'first'" />
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10" type="flex" align="middle" justify="space-between">
          <el-col :span="24">
            <h3>社区报警数量和设备安装数量top对比</h3>
            <div :style="styleObject">
              <ECharts :options="top" v-if="activeName === 'first'" />
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="入户监测列表" name="second">
        <div class="user-table">
          <el-table
            :data="tableData"
            max-height="500"
            style="width: 100%; font-size: 16px"
            v-loading="loading"
            :header-cell-style="tableHeaderColor"
            element-loading-background="rgba(0,0,0,0.2)"
            :row-style="{ height: '50px' }"
            :cell-style="{ padding: '0px' }"
            ref="scrollTable"
          >
            <el-table-column
              v-for="(item, index) in column"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :min-width="item.width"
              :align="item.align"
              show-overflow-tooltip
            >
              <template #default="scope">
                <el-button link v-if="item.prop === 'set' && scope.row.is_alarmed === '1'" @click="alarmRecordHandle(scope.row)">
                  处理记录
                </el-button>
                <span v-else>{{ scope.row[item.prop] }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" v-model:page="params.pageNo" v-model:limit="params.pageSize" @pagination="getList" />
        </div>
        <alarm-record v-model="alarmRecordFlag" ref="alarmRecordRef" />
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import {
  getHouseholdMonitoring,
  getTongji,
  getHouseByCounty,
  getAlarmByAlarmCounty,
  getAlarmByCountyAndHouse,
  getAlarmByTime,
  getAlarmByAlarmTop
} from '@/api/monitoringForce';
import AlarmRecord from './alarmRecord/index.vue';
import ECharts from './echarts/index.vue';
import { riskStatusOption, topOption, CountyOption, AlarmCountyOption, CountyAndHouseOption, AlarmByTimeOption } from './config';
import topIcon1 from '@/assets/largescreen/top-icon1.png';
import topIcon2 from '@/assets/largescreen/top-icon2.png';
import topIcon3 from '@/assets/largescreen/top-icon3.png';
import topIcon4 from '@/assets/largescreen/top-icon4.png';

interface TableColumn {
  label: string;
  prop: string;
  width: string;
  align: string;
}

interface ProjectNumItem {
  name: string;
  num: string | number;
  icon: string;
}

interface TableRow {
  [key: string]: any;

  is_alarmed?: string;
  meter_id?: string;
}

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '入户监测'
  }
});

const emit = defineEmits(['close']);

// 数据状态
const tableData = ref<TableRow[]>([]);
const total = ref(0);
const loading = ref(false);
const alarmRecordFlag = ref(false);
const activeName = ref('first');
const scrollTable = ref();
const alarmRecordRef = ref();

// 参数
const params = reactive({
  pageNo: 1,
  pageSize: 10
});

// 样式和配置
const styleObject = reactive({
  width: '100%',
  height: '300px'
});

const column = ref<TableColumn[]>([
  { label: '户号', prop: 'household_id', width: '120', align: 'center' },
  { label: '用户名', prop: 'user_name', width: '120', align: 'center' },
  { label: '表号', prop: 'meter_id', width: '120', align: 'center' },
  { label: '居委会', prop: 'community_committee', width: '120', align: 'center' },
  { label: '小区', prop: 'residential_area', width: '120', align: 'center' },
  { label: '楼栋', prop: 'building_number', width: '120', align: 'center' },
  { label: '地址', prop: 'address', width: '120', align: 'center' },
  { label: '表具类型代码', prop: 'meter_type_code', width: '120', align: 'center' },
  { label: '表具厂家', prop: 'meter_manufacturer', width: '120', align: 'center' },
  { label: '表具类型', prop: 'meter_type', width: '120', align: 'center' },
  { label: '用户状态', prop: 'user_status', width: '120', align: 'center' },
  { label: '微小流量监测', prop: 'set', width: '160', align: 'center' }
]);

const projectNum = ref<ProjectNumItem[]>([
  { name: '设备总数', num: 0, icon: topIcon1 },
  { name: '微小流报警总数', num: 0, icon: topIcon2 },
  { name: '报警处置数', num: 0, icon: topIcon3 },
  { name: '处置率', num: 0, icon: topIcon4 }
]);

// 图表数据
const chartData = reactive({
  riskStatus: { ...riskStatusOption },
  top: { ...topOption },
  County: { ...CountyOption },
  AlarmCounty: { ...AlarmCountyOption },
  CountyAndHouse: { ...CountyAndHouseOption },
  AlarmByTime: { ...AlarmByTimeOption }
});

// 方法
const getList = async () => {
  try {
    loading.value = true;

    // 并行请求所有数据
    const [tableRes, tongjiRes, houseByCountyRes, alarmByAlarmCountyRes, alarmByCountyAndHouseRes, alarmByTimeRes, alarmByAlarmTopRes] =
      await Promise.all([
        getHouseholdMonitoring(params),
        getTongji(),
        getHouseByCounty(),
        getAlarmByAlarmCounty(),
        getAlarmByCountyAndHouse(),
        getAlarmByTime(),
        getAlarmByAlarmTop()
      ]);

    // 处理表格数据
    if (tableRes.data === 'null') {
      tableData.value = [];
      total.value = 0;
    } else {
      tableData.value = JSON.parse(tableRes.data).records;
      total.value = JSON.parse(tableRes.data).totalCount;
    }

    // 处理统计数据
    projectNum.value[0].num = tongjiRes.data.sum;
    projectNum.value[1].num = tongjiRes.data.alarmSum;
    projectNum.value[2].num = tongjiRes.data.alarmDisposeSum;
    projectNum.value[3].num = `${tongjiRes.data.alarmDisposeRate}%`;

    // 处理图表数据
    chartData.County.xAxis.data = Object.keys(houseByCountyRes.data);
    chartData.County.series[0].data = Object.values(houseByCountyRes.data);

    chartData.AlarmCounty.xAxis.data = Object.keys(alarmByAlarmCountyRes.data);
    chartData.AlarmCounty.series[0].data = Object.values(alarmByAlarmCountyRes.data);

    // 处理各区县设备安装数量和报警数量数据
    chartData.CountyAndHouse.xAxis.data = alarmByCountyAndHouseRes.data.county;
    chartData.CountyAndHouse.series[0].data = alarmByCountyAndHouseRes.data.police;
    chartData.CountyAndHouse.series[1].data = alarmByCountyAndHouseRes.data.equipment;

    chartData.AlarmByTime.xAxis.data = Object.keys(alarmByTimeRes.data);
    chartData.AlarmByTime.series[0].data = Object.values(alarmByTimeRes.data);

    chartData.top.xAxis.data = [];
    chartData.top.series[0].data = [];
    chartData.top.series[1].data = [];
    alarmByAlarmTopRes.data.forEach((item) => {
      chartData.top.xAxis.data.push(item.communityCommittee);
      chartData.top.series[0].data.push(item.su);
      chartData.top.series[1].data.push(item.size);
    });
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
};

const alarmRecordHandle = (row: TableRow) => {
  alarmRecordFlag.value = true;
  alarmRecordRef.value.params.resid = row.meter_id;
  alarmRecordRef.value.getList();
};

const tableHeaderColor = ({ rowIndex }: { rowIndex: number }) => {
  if (rowIndex === 0) {
    return { color: '#00FFFF' };
  }
  return {};
};

const handleClose = () => {
  params.pageNo = 1;
  params.pageSize = 10;
  tableData.value = [];
  total.value = 0;
  loading.value = false;
  emit('close');
};

const handleQuery = () => {
  params.pageNo = 1;
  getList();
};

const resetQuery = () => {
  params.pageNo = 1;
  params.pageSize = 10;
  getList();
};

const handleClick = () => {
  // 处理tab点击事件
};

// 计算属性
const { County, AlarmCounty, CountyAndHouse, AlarmByTime, top } = chartData;

// 初始化获取数据
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      getList();
    }
  },
  { immediate: true }
);

// 关键！暴露属性和方法
defineExpose({
  getList
});
</script>

<style scoped lang="scss">
.card-box {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 10px 20px;
  box-sizing: border-box;

  .card-item {
    width: 15%;
    height: 100px;
    background-color: #0655cc;
    border-radius: 10px;
    display: flex;
    align-items: center;
    padding: 0px 20px;
    box-sizing: border-box;

    img {
      width: 30%;
    }

    .card-item-content {
      min-width: 75%;
      margin-left: 15px;

      .num {
        font-size: 24px;
        font-weight: 600;
        color: #00ffff;
      }

      .name {
        font-size: 14px;
        font-weight: 600;
        color: #00ffff;
      }
    }
  }
}

.user-table {
  :deep(.el-table) {
    --el-table-border-color: #004e70;
    --el-table-header-bg-color: transparent;
    --el-table-row-hover-bg-color: transparent;
    --el-table-text-color: #fff;
    --el-table-header-text-color: #00ffff;
    --el-table-border: none;

    background-color: transparent;

    /* 全局样式中 */
    .el-table__header-wrapper th {
      background: linear-gradient(180deg, #004db9 0%, #01347b 48%, #014cb5 100%);
      color: #0ff;
    }

    .el-table__body {
      tr {
        background-color: #083577;
        color: #fff;

        td {
          border-bottom: 1px solid #0a73a0;
          cursor: pointer;
        }
      }
    }

    .el-table__empty-block {
      background-color: #003556;

      .el-table__empty-text {
        color: #00ffff;
        font-size: 24px;
      }
    }

    /* Scrollbar styles */
    .el-table__body-wrapper {
      &::-webkit-scrollbar {
        width: 0.5rem;
        height: 0.5rem;
        background-color: #3f8af3;
        border-radius: 0.375rem;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #1c4682;
        border-radius: 0.375rem;
      }
    }
  }

  .pagination-container {
    background: #083577;
    padding: 10px 16px;
    text-align: right;
    margin: 0;
  }

  .pagination-container.hidden {
    display: none;
  }

  :deep(.el-pagination__total) {
    color: #fff;
  }

  :deep(.el-pagination__jump) {
    color: #fff;
  }

  .el-button {
    color: #00ffff;
  }
}
</style>

<style lang="scss">
.userAlarm-dialog {
  padding: 0 !important;

  .el-dialog__header {
    padding: 20px;
    background-color: #083577;

    .el-dialog__title {
      color: #0be4f1;
    }
  }

  .el-dialog__body {
    background-color: #083577;
    padding: 20px;
  }
}

.tabs-box {
  color: #ffffff;
  width: 100%;

  .chart-box {
    width: 100%;
  }

  .el-tabs__item {
    font-family: PangMenZhengDao;
    color: #409eff;
  }

  .el-tabs__item.is-active {
    color: #00ffff !important;
  }

  .el-tabs__active-bar {
    background-color: #00ffff !important;
  }

  .el-tabs__nav-wrap::after {
    position: static !important;
  }
}
</style>
